from django.shortcuts import render, get_object_or_404, redirect
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.utils.text import slugify
from .models import Tool, ToolCategory, ToolTag, ToolReview
from .forms import ToolForm

def tool_list(request):
    """工具列表视图"""
    tools = Tool.objects.filter(status='active')
    
    # 搜索功能
    search_query = request.GET.get('search')
    if search_query:
        tools = tools.filter(
            Q(name__icontains=search_query) |
            Q(description__icontains=search_query)
        )
    
    # 分类筛选
    category_slug = request.GET.get('category')
    if category_slug:
        tools = tools.filter(category__slug=category_slug)
    
    # 工具类型筛选
    tool_type = request.GET.get('type')
    if tool_type:
        tools = tools.filter(tool_type=tool_type)
    
    # 标签筛选
    tag_slug = request.GET.get('tag')
    if tag_slug:
        tools = tools.filter(tooltag__slug=tag_slug)
    
    # 排序
    sort_by = request.GET.get('sort', '-created_at')
    if sort_by in ['-created_at', '-views', '-clicks', '-rating', 'name']:
        tools = tools.order_by(sort_by)
    
    # 分页
    paginator = Paginator(tools, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 获取侧边栏数据
    categories = ToolCategory.objects.all()
    tags = ToolTag.objects.all()
    featured_tools = Tool.objects.filter(is_featured=True, status='active')[:5]
    
    context = {
        'page_obj': page_obj,
        'categories': categories,
        'tags': tags,
        'featured_tools': featured_tools,
        'search_query': search_query,
        'current_category': category_slug,
        'current_type': tool_type,
        'current_tag': tag_slug,
        'current_sort': sort_by,
    }
    
    return render(request, 'tools/tool_list.html', context)

def tool_detail(request, slug):
    """工具详情视图"""
    tool = get_object_or_404(Tool, slug=slug, status='active')
    
    # 增加浏览次数
    tool.increment_views()
    
    # 获取相关工具
    related_tools = Tool.objects.filter(
        category=tool.category,
        status='active'
    ).exclude(id=tool.id)[:4]
    
    # 获取评价
    reviews = tool.reviews.filter(is_approved=True)
    
    context = {
        'tool': tool,
        'related_tools': related_tools,
        'reviews': reviews,
    }
    
    return render(request, 'tools/tool_detail.html', context)

def category_detail(request, slug):
    """工具分类详情视图"""
    category = get_object_or_404(ToolCategory, slug=slug)
    tools = Tool.objects.filter(category=category, status='active')
    
    # 分页
    paginator = Paginator(tools, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'category': category,
        'page_obj': page_obj,
    }
    
    return render(request, 'tools/category_detail.html', context)

def tool_click(request, slug):
    """工具点击统计"""
    if request.method == 'POST':
        tool = get_object_or_404(Tool, slug=slug, status='active')
        tool.increment_clicks()
        return JsonResponse({'status': 'success'})
    return JsonResponse({'status': 'error'})

def ajax_tool_search(request):
    """AJAX工具搜索"""
    query = request.GET.get('q', '')
    if query:
        tools = Tool.objects.filter(
            Q(name__icontains=query) | Q(description__icontains=query),
            status='active'
        )[:10]
        
        results = []
        for tool in tools:
            results.append({
                'name': tool.name,
                'url': tool.get_absolute_url(),
                'description': tool.description[:100] + '...' if len(tool.description) > 100 else tool.description,
                'icon': tool.icon,
            })
        
        return JsonResponse({'results': results})
    
    return JsonResponse({'results': []})

@login_required
def tool_create(request):
    """创建工具视图"""
    if request.method == 'POST':
        form = ToolForm(request.POST, request.FILES)
        if form.is_valid():
            tool = form.save(commit=False)
            tool.author = request.user
            # 自动生成slug
            if not tool.slug:
                tool.slug = slugify(tool.name)
            tool.save()
            messages.success(request, '工具创建成功！')
            return redirect('tools:tool_detail', slug=tool.slug)
    else:
        form = ToolForm()
    
    return render(request, 'tools/tool_form.html', {
        'form': form,
        'title': '创建工具',
        'action': '创建'
    })

@login_required
def tool_edit(request, slug):
    """编辑工具视图"""
    tool = get_object_or_404(Tool, slug=slug)
    
    # 检查权限：只有作者或管理员可以编辑
    if tool.author != request.user and not request.user.is_staff:
        messages.error(request, '您没有权限编辑此工具。')
        return redirect('tools:tool_detail', slug=slug)
    
    if request.method == 'POST':
        form = ToolForm(request.POST, request.FILES, instance=tool)
        if form.is_valid():
            form.save()
            messages.success(request, '工具更新成功！')
            return redirect('tools:tool_detail', slug=tool.slug)
    else:
        form = ToolForm(instance=tool)
    
    return render(request, 'tools/tool_form.html', {
        'form': form,
        'tool': tool,
        'title': f'编辑工具 - {tool.name}',
        'action': '更新'
    })

@login_required
def tool_delete(request, slug):
    """删除工具视图"""
    tool = get_object_or_404(Tool, slug=slug)
    
    # 检查权限：只有作者或管理员可以删除
    if tool.author != request.user and not request.user.is_staff:
        messages.error(request, '您没有权限删除此工具。')
        return redirect('tools:tool_detail', slug=slug)
    
    if request.method == 'POST':
        tool.delete()
        messages.success(request, '工具删除成功！')
        return redirect('tools:tool_list')
    
    return render(request, 'tools/tool_confirm_delete.html', {
        'tool': tool
    })
